#!/usr/bin/env python3
# -*- coding: utf-8 -*-

from configparser import ConfigParser
from logging import info
from os import environ
from os.path import join
from typing import Union

CONFIG_FILE = join(environ.get('LOCALAPPDATA'), 'haishen_print.ini')

class Config(object):

	config: ConfigParser
	dirty: bool = False

	def __init__(self) -> None:
		self.config = ConfigParser()
		info('Reading config file %s', CONFIG_FILE)
		self.config.read(CONFIG_FILE)

	def get(self, section: str, option: str) -> Union[str, None]:
		return self.config.get(section, option, fallback=None)

	def set(self, section: str, option: str, value: str) -> None:
		if not self.config.has_section(section):
			self.config.add_section(section)
		self.config.set(section, option, value)
		self.dirty = True

	def __enter__(self):
		return self

	def __exit__(self, exc_type, exc_value, traceback):
		if self.dirty:
			with open(CONFIG_FILE, 'wt') as config_file:
				info('Writing to config file %s', CONFIG_FILE)
				self.config.write(config_file, space_around_delimiters=False)
